const jwt = require('jsonwebtoken');
require('dotenv').config();

const authMiddleware = (req, res, next) => {
    try {
        // 从请求头获取token
        const authHeader = req.headers.authorization;
        
        if (!authHeader || !authHeader.startsWith('Bearer ')) {
            return res.status(401).json({
                success: false,
                message: '未提供认证令牌'
            });
        }
        
        const token = authHeader.substring(7); // 移除 'Bearer ' 前缀
        
        // 验证token
        const decoded = jwt.verify(token, process.env.JWT_SECRET || 'fun_english_secret_key_2025_lycc_top');
        
        // 将用户信息附加到请求对象
        req.user = {
            id: decoded.id,
            username: decoded.username,
            grade: decoded.grade,
            isAdmin: decoded.isAdmin || false,
            role: decoded.role
        };
        
        next();
    } catch (error) {
        if (error.name === 'TokenExpiredError') {
            return res.status(401).json({
                success: false,
                message: '认证令牌已过期'
            });
        }
        
        return res.status(401).json({
            success: false,
            message: '无效的认证令牌'
        });
    }
};

module.exports = {
    authenticate: authMiddleware,
    authMiddleware
};

